package net.xdclass.demoproject.controller;

import net.xdclass.demoproject.config.WXConfig;
import net.xdclass.demoproject.task.AsyncTask;
import net.xdclass.demoproject.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("api/v1/test")
@PropertySource({"classpath:pay.properties"})
public class TestController {


    @Value("${wxpay.appid}")
    private String payAppid;

    @Value("${wxpay.secret}")
    private String paySecret;


    //配置文件与实体类映射方式2,直接注入后便可拿到对象中的值
    @Autowired
    private WXConfig wxConfig;

    @Autowired
    private AsyncTask asyncTask;


    /**
     * 测试异步方法:可以比较下不加异步注解与加上这个异步注解分别调用这个接口的时间
     * 加上异步注解后:
     *    基本上先返回JsonData.buildSuccess( end - begin);然后在非顺序执行test1 2 3方法
     *
     * localhost:8080/api/v1/test/async
     * @return
     */
    @GetMapping("async")
    public JsonData testAsync(){

        long begin = System.currentTimeMillis();
//        asyncTask.task1();
//        asyncTask.task2();
//        asyncTask.task3();
        //获取异步任务返回结果,用无线循环+isDone()方法来实现
        Future<String> task4 =  asyncTask.task4();
        Future<String> task5 =  asyncTask.task5();
        for(;;){
            if(task4.isDone() && task5.isDone()){
                try {
                    String task4Result = task4.get();
                    System.out.println(task4Result);
                    String task5Result = task5.get();
                    System.out.println(task5Result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }finally {
                    break;
                }
            }
        }
        long end = System.currentTimeMillis();
        return JsonData.buildSuccess( end - begin);
    }

    @GetMapping("get_config")
    public JsonData testConfig(){
        //方式1
       Map<String,String> map = new HashMap<>();
//        map.put("appid",payAppid);
//        map.put("secret",paySecret);
//        return JsonData.buildSuccess(map);

        //方式2
        map.put("appid",wxConfig.getPayAppid());
        map.put("secret",wxConfig.getPaySecret());
        map.put("mechid",wxConfig.getPayMechId());
        return JsonData.buildSuccess(map);
    }

    //跳转到全局异常处理页面测试
    @GetMapping("test")
    public void testCustomerHandler(){
        System.out.println(1/0);
    }


}
